package com.tianji.aigc.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tianji.aigc.config.SystemPromptConfig;
import com.tianji.aigc.config.ToolResultHolder;
import com.tianji.aigc.constants.Constant;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.service.ChatSessionService;
import com.tianji.aigc.vo.ChatEventVO;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RequiredArgsConstructor
@Slf4j
@Service
@ConditionalOnProperty(prefix = "tj.ai", name = "chat-type", havingValue = "ENHANCE")
public class ChatServiceImpl implements ChatService {

    private final ChatClient chatClient;
    private final SystemPromptConfig systemPromptConfig;
    private final ChatMemory redisChatMemory;
    private final VectorStore vectorStore;
    private final ChatSessionService chatSessionService;
    // 作为一个全局的、线程安全的状态存储，用来标记特定 sessionId 对应的对话生成任务是否应该继续进行
    // Key: sessionId，唯一标识一个用户的会话
    // Value: Boolean，true 表示生成任务应该继续，false 或 null (通过 getOrDefault) 表示生成任务应该被停止
    // 目前的版本暂时用Map实现，如果考虑分布式环境的话，可以考虑用redis来实现
    // ConcurrentHashMap是线程安全的
    private static final Map<String, Boolean> GENERATE_STATUS = new ConcurrentHashMap<>();
    //输出结束的标记
    private static final ChatEventVO STOP_EVENT = ChatEventVO.builder().eventType(ChatEventTypeEnum.STOP.getValue()).build();

    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
        String conversationId = ChatService.getConversationId(sessionId);
        StringBuilder outputBuilder = new StringBuilder();
        String requestId = IdUtil.fastSimpleUUID();
        Long userId = UserContext.getUser();
        // 创建RAG增强
        QuestionAnswerAdvisor qaAdvisor = QuestionAnswerAdvisor.builder(this.vectorStore)
                .searchRequest(SearchRequest.builder().similarityThreshold(0.6d).topK(5).build())
                .build();
        //chatSessionService.update(sessionId,question,userId);


        return chatClient.prompt()
                // 设置系统提示语
                .system(promptSystemSpec -> promptSystemSpec
                        .text(this.systemPromptConfig.getSystemPrompt().get())
                        .param("now", DateUtil.now()))//设置当前时间的参数
                .user( question)
                .advisors(advisor -> advisor.advisors(qaAdvisor) // 设置RAG增强
                        .param(ChatMemory.CONVERSATION_ID, conversationId))
                .toolContext(Map.of(Constant.REQUEST_ID,requestId,Constant.USER_ID,userId))//生成课程卡片第一步，通过工具上下文传递参数
                .stream()
                .chatResponse()
                //新增用于实现终端的关键操作符
                .doFirst(()->GENERATE_STATUS.put(sessionId, true))//第一次运行时，将sessionId对应的状态设置为true
                .doOnError(throwable -> GENERATE_STATUS.remove(sessionId))//错误时，将sessionId对应状态设置为null
                .doOnComplete(()->GENERATE_STATUS.remove(sessionId))//完成时，将sessionId对应状态设置为null
                .doOnCancel(()-> saveStopHistoryRecord(conversationId, outputBuilder))//取消时，将内容填充到redis中
                .takeWhile(response -> {//循环判断sessionId对应状态是否为true
                    return GENERATE_STATUS.getOrDefault(sessionId, false);
                })
                .doFinally(signalType -> {
                    String title = StrUtil.concat(true,
                            "问：",question,",答：", outputBuilder.toString());
                    chatSessionService.update(sessionId, title, userId);
                })
                .map(chatResponse -> {

                    // 对于响应结果进行处理，如果是最后一条数据，就把此次消息requestId放到内存中
                    // 主要用于存储param（卡片数据）到 redis中，可以根据消息id获取的请求id，再通过请求id就可以获取到参数列表了
                    // 从而解决，在历史聊天记录中没有外参数的问题
                    String finishReason = chatResponse.getResult().getMetadata().getFinishReason();
                    if (StrUtil.equals(Constant.STOP, finishReason)){
                        String messageId = chatResponse.getMetadata().getId();
                        ToolResultHolder.put(messageId,Constant.REQUEST_ID,requestId);
                    }


                    //获取大模型输出的内容
                    String text = chatResponse.getResult().getOutput().getText();
                    //追加到输出内容中
                    outputBuilder.append(text);
                    //封装相应对象
                    return ChatEventVO.builder()
                            .eventData(text)
                            .eventType(ChatEventTypeEnum.DATA.getValue())
                            .build();
                })
                //添加停止事件
                .concatWith(Flux.defer(()->{//延迟创建流
                    //先获取输出内容
                    Map<String, Object> map = ToolResultHolder.get(requestId);
                    if (CollUtil.isNotEmpty( map)){
                        //将参数封装到相应对象中
                        ChatEventVO chatEventVO = ChatEventVO.builder()
                                .eventData(map)
                                .eventType(ChatEventTypeEnum.PARAM.getValue())
                                .build();
                        //删除旧参数
                        ToolResultHolder.remove(requestId);
                        //返回结果
                        return Flux.just(chatEventVO, STOP_EVENT);
                    }else {
                        return Flux.just(STOP_EVENT);
                    }
                }));
    }

    /**
     * 保存停止事件记录
     * @param conversationId 会话ID
     * @param outputBuilder 输出内容
     */
    private void saveStopHistoryRecord(String conversationId, StringBuilder outputBuilder) {
        redisChatMemory.add(conversationId, new AssistantMessage(outputBuilder.toString()));
    }

    @Override
    public void stop(String sessionId) {
        GENERATE_STATUS.remove(sessionId);
    }
}
